const net = require('net');
const LISTEN_PORT = process.argv[2] || 11185;

net.createServer(c => {

        c.end(getCurrentFormattedDate() + '\r\n');

        c.on('data', data => {
            console.log(data.toString());
        });

        c.on('data', data => {
            if (data.toString() === 't') {
                c.write(getCurrentFormattedDate(), () => {
                    console.log('all data is sent @ ' + getCurrentFormattedDate());
                });
            }
        });

    })
    .on('err', console.error)
    .listen(LISTEN_PORT);

function getCurrentFormattedDate() {
    let date = new Date();
    return date.getFullYear() + '-' + formatTo2Byte(date.getMonth() + 1) + '-' + formatTo2Byte(date.getDate()) + ' ' + formatTo2Byte(date.getHours()) + ':' + formatTo2Byte(date.getMinutes());
}

function formatTo2Byte(number) {
    return number < 10 ? '0' + number : number;
}